package com.token.iot.bratterycharging.gateway.business;

import java.util.Map;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.Oper;

import com.token.iot.bratterycharging.gateway.Semaphore;
import com.token.iot.bratterycharging.gateway.SemaphoreManager;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.sender.AABSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 双通道
 * 
 * @author chenzhixuan
 *
 */
public abstract class DuplexProcessor implements Sender, Oper {

	protected static Logger loger = LoggerFactory.getLogger("transactionLogger");

	protected ChannelHandlerContext context;

	protected String code;

	public ChannelHandlerContext getContext() {
		return context;
	}

	public void setContext(ChannelHandlerContext context) {
		this.context = context;
	}

	@Override
	public String getCode() {
		return this.code;
	}

	@Override
	public void setCode(String code) {
		this.code = code;
	}

	@Override
	public Object send(String imei, Map<String, String> params) throws PendingException {
		// 先从指令集合中拿拿去到对应的指令
		String str = request(imei, params);
		return str;
	}
	
	
	//返回0 没有后续响应调用，这个实际上是双通道的实际响应逻辑。
	@Override
	public int onCall(byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		loger.info(" the " + this.getClass() + " Mes =" + val);
		String imei = IMEI.getIMEI(ctx);
		String sessionid = IDGeneration.getSessionID(b);
		loger.info(" the " + this.getClass() + " sessionid =" + sessionid);
		String key = imei + "@" + sessionid;
		SemaphoreManager.onResponse(key, val);
		return 0;

	}

	abstract public String request(String imei, Map<String, String> params) throws PendingException;

	abstract public Object response(String response) throws PendingException;
}
